package com.xhtranslate.service.youdao.serviceImpl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhtranslate.common.config.TranslateConfig;
import com.xhtranslate.common.dto.ImageFormDTO;
import com.xhtranslate.common.dto.TextFormDTO;
import com.xhtranslate.common.util.JudgeCreditLimitUtil;
import com.xhtranslate.common.util.AddUseLimitThreadUtil;
import com.xhtranslate.common.vo.ResponseEnum;
import com.xhtranslate.service.youdao.service.YoudaoOcrService;
import com.xhtranslate.service.youdao.service.YoudaoTranslateService;
import com.xhtranslate.service.youdao.util.YoudaoUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 有道翻译impl
 *
 * @author liuxuhuang
 * @date 2022/11/17 15:22:33
 */
@Service
@Slf4j
public class YoudaoTranslateImpl implements YoudaoTranslateService {
    @Autowired
    private YoudaoOcrService youdaoOcrService;
    @Autowired
    private YoudaoUtil youdaoUtil;
    @Autowired
    private JudgeCreditLimitUtil judgeCreditLimitUtil;
    @Autowired
    private AddUseLimitThreadUtil addUseLimitThreadUtil;
    /**
     * 特殊字符匹配
     */
    private Pattern stringPattern = Pattern.compile(TranslateConfig.SpecialString);

    @Override
    public Map commonTranslate(TextFormDTO dto) throws IOException {
        Matcher matcher = stringPattern.matcher(dto.getContext());
        String trim = matcher.replaceAll("-").trim();
        String salt = String.valueOf(System.currentTimeMillis());
        String curtime = String.valueOf(System.currentTimeMillis() / 1000);
        String signStr = TranslateConfig.YoudaoAppId + youdaoUtil.truncate(trim) + salt +
                curtime + TranslateConfig.YoudaoSecreKey;
        String sign = youdaoUtil.getDigest(signStr);
        Map<String, String> params = packingParams(trim, dto.getFrom(), dto.getTo(), curtime, sign, salt);
        String res = youdaoUtil.requestForHttp(TranslateConfig.YoudaoTextRequestUrl, params);
        JSONObject object = JSONObject.parseObject(res);
        Map map = new HashMap();
        if (!"0".equals(object.getString("errorCode"))) {
            return map;
        }
        JSONArray jsonArray = object.getJSONArray("translation");
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < jsonArray.size(); i++) {
            stringBuffer.append(jsonArray.get(i)).append("\n");
        }
        addUseLimitThreadUtil.addCreditLimit(TranslateConfig.YoudaoTextTranslateRedisName, stringBuffer.length());
        map.put("errorCode", 0);
        map.put("translation", stringBuffer);
        map.put("fromTTSUrl", object.getString("tSpeakUrl"));
        map.put("toTTSUrl", object.getString("speakUrl"));
        return map;
    }

    @Override
    public Map imageTranslate(ImageFormDTO dto) throws IOException {
        Map<String, String> map = youdaoOcrService.ocrImg(dto.getFile());
        String errorCode = map.get("errorCode");
        String ocrImgString = map.get("data");
        if (!"0".equals(errorCode)) {
            return map;
        }
        if (StringUtils.isBlank(ocrImgString)) {
            return map;
        }
        log.info("有道图片翻译前：" + ocrImgString);
        boolean b = judgeCreditLimitUtil.getBeyondTextCredit(TranslateConfig.YoudaoTextTranslateRedisName, TranslateConfig.YoudaoTextTranslateRedisCreditLimit, ocrImgString.length());
        if (!b) {
            map.clear();
            map.put("errorCode", String.valueOf(ResponseEnum.OVERCREDITLIMIT.getCode()));
            return map;
        }
        TextFormDTO textFormDTO = new TextFormDTO(dto.getPlatform(), dto.getFrom(), dto.getTo(), ocrImgString);
        Map translateMap = commonTranslate(textFormDTO);
        translateMap.put("errorCode", "0");
        log.warn("有道图片翻译后：" + translateMap.toString());
        return translateMap;
    }

    public Map<String, String> packingParams(String text, String from, String to,
                                             String curtime, String sign, String salt) {
        Map<String, String> params = new HashMap<>();
        params.put("q", text);
        params.put("from", from);
        params.put("to", to);
        params.put("signType", "v3");
        params.put("curtime", curtime);
        params.put("appKey", TranslateConfig.YoudaoAppId);
        params.put("salt", salt);
        params.put("sign", sign);
        return params;
    }
}
